package user

import (
	"errors"
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/bgmp/service"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"strconv"
	"time"
)

func (b Base) SelectCols(c *gin.Context, req *ColsRequest) []string {
	i := req.Sid
	sid, err := model.ParseSid(i)
	if err != nil || sid == 0 {
		handler.ReplyError(c, http.StatusBadRequest, "arg[Sid] is invalid")
		c.Abort()
		return nil
	}
	f := &model.File{}
	f.Sid = sid
	err = f.Get(config.DB)
	if err != nil {
		handler.ReplyError(c, http.StatusBadRequest, "file is not found")
		c.Abort()
		return nil
	}
	excel, err := service.OpenExcel(f.Link)
	if err != nil {
		log.Error(err)
		handler.ReplyError(c, http.StatusInternalServerError, "failed to open file")
		c.Abort()
		return nil
	}
	defer excel.Close()

	sheet := excel.GetSheetList()[0]

	rows, err := excel.GetRows(sheet)
	if err != nil {
		handler.ReplyError(c, http.StatusInternalServerError, "failed to read excel")
		c.Abort()
		return nil
	}
	return rows[0]
}

type ColsRequest struct {
	Sid string `json:"sid"`
}

func (b Base) LoadData(c *gin.Context, req *FileDataRequest) *struct{} {
	i := req.Sid
	userId := req.UserID
	if userId == 0 {
		userId = middleware.GetUserId(c)
	}

	err := saveData(i, req.Time, req.Value, userId)
	if err != nil {
		handler.ReplyError(c, http.StatusBadRequest, err.Error())
		return nil
	}

	return &struct{}{}
}

type FileDataRequest struct {
	Sid    string `json:"sid"`
	Time   string `json:"time"`
	Value  string `json:"value"`
	UserID uint   `json:"user_id"`
}

func tryParseTime(str string) (time.Time, error) {
	t, err := time.ParseInLocation(`2006/01/02 15:04:05`, str+":00", time.Local)
	if err == nil {
		return t, nil
	}

	t, err = time.ParseInLocation(`2006-01-02T15:04:05`, str, time.Local)
	return t, err
}

func saveData(fid string, t string, value string, userId uint) error {
	sid, err := model.ParseSid(fid)
	if err != nil || sid == 0 {
		return errors.New("arg[Sid] is invalid")
	}
	f := &model.File{}
	f.Sid = sid
	err = f.Get(config.DB)
	if err != nil {
		return errors.New("file is not found")
	}
	excel, err := service.OpenExcel(f.Link)
	if err != nil {
		return errors.New("failed to open file")
	}

	sheet := excel.GetSheetList()[0]

	times := make([]string, 0)
	values := make([]string, 0)
	cols, err := excel.Cols(sheet)
	_ = excel.Close()

	for cols.Next() {
		col, _ := cols.Rows()
		if col[0] == t {
			times = col[1:]
		} else if col[0] == value {
			values = col[1:]
		}
	}
	//fmt.Println(times)
	//fmt.Println(values)

	bgs := make([]*model.Bg, 0)
	length := len(times)
	lengthV := len(values)
	if lengthV < length {
		length = lengthV
	}

	if length <= 0 {
		return errors.New("错误的列号!")
	}

	for index := 0; index < length; index++ {
		if values[index] == "" {
			continue
		}
		v, err := strconv.ParseFloat(values[index], 64)
		if err != nil {
			log.Errorf("解析 %s 为浮点型失败", values[index])
			continue
		}

		if v > 50 {
			v /= service.MG_L_TO_MMOL_L
		}

		actualTime, err := tryParseTime(times[index])
		if err != nil {
			log.Errorf("解析 %s 为时间格式失败", times[index])
			continue
		}
		bgs = append(bgs, &model.Bg{
			BgMeta: model.BgMeta{
				UserId: userId,
			},
			BgField: model.BgField{
				Time:  actualTime,
				Value: v,
				Type:  1,
			},
		})
	}

	err = model.SaveBgsFromFile(bgs)
	if err != nil {
		return errors.New("failed to save file")
	}
	return nil
}

func (b Base) LoadDataFromSpecificFile(c *gin.Context, req *LoadDataFromSpecificFileRequest) *struct{} {
	t := ""
	value := ""
	switch req.Category {
	case "小贝壳":
		t = "时间"
		value = "数值"
	case "瞬感":
		t = "时间"
		value = "葡萄糖历史记录（mmol/L）"
	default:
		handler.ReplyError(c, http.StatusOK, "暂未支持")
		return nil
	}

	err := saveData(req.Sid, t, value, req.UserID)
	if err != nil {
		handler.ReplyError(c, http.StatusOK, err.Error())
		return nil
	}
	return &struct{}{}
}

type LoadDataFromSpecificFileRequest struct {
	Sid      string `json:"sid"`
	UserID   uint   `json:"user_id"`
	Category string `json:"category"`
}
